package com.shenda.api.dao;

import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.shenda.api.entity.Gyro;
import com.swak.entity.Page;
import com.swak.entity.Parameters;
import com.swak.persistence.BaseJdbcDao;
import com.swak.persistence.QueryCondition;
import com.swak.utils.Maps;
import com.swak.utils.StringUtils;

/**
 * 数据库存储操作
 * 
 * @author lifeng
 */
@Repository
public class GyroDao extends BaseJdbcDao {

	/**
	 * 通过ID获取
	 * 
	 * @param id
	 * @return
	 */
	public Gyro get(String id) {
		Map<String, Object> param = Maps.newHashMap();
		param.put("id", StringUtils.defaultIfBlank(id, StringUtils.EMPTY));
		return this.get("SELECT ID, NAME, CJMS, CJPL, ODR, LASTFLUSHTIME FROM GYRO WHERE ID = :id", param,
				this.getRowMapper());
	}

	/**
	 * 插入
	 * 
	 * @param id
	 * @return
	 */
	public void insert(Gyro gyro) {
		Gyro old = this.get(gyro.getId());
		if (old == null) {
			Map<String, Object> param = this.BeantoMap(gyro);
			this.insert("REPLACE INTO GYRO(ID, NAME) VALUES(:id, :name)", param);
		}
	}

	/**
	 * 修改配置项
	 * 
	 * @param id
	 * @return
	 */
	public void updateSettings(Gyro gyro) {
		Map<String, Object> param = this.BeantoMap(gyro);
		this.update("UPDATE GYRO SET CJMS = :cjms, CJPL = :cjpl, ODR = :odr WHERE ID = :id", param);
	}

	/**
	 * 修改最后一次清除数据时间
	 * 
	 * @param id
	 * @return
	 */
	public void updateFlush(Gyro gyro) {
		Map<String, Object> param = this.BeantoMap(gyro);
		this.insert("UPDATE GYRO SET LASTFLUSHTIME = :lastFlushTime WHERE ID = :id)", param);
	}

	/**
	 * 分页查询
	 * 
	 * @param gyro
	 * @param param
	 * @return
	 */
	public Page page(QueryCondition query, Parameters param) {
		String sql = "SELECT ID, NAME, CJMS, CJPL, ODR, LASTFLUSHTIME FROM GYRO";
		return this.page(sql, query, param, this.getRowMapper());
	}

	/**
	 * 数据转换
	 * 
	 * @return
	 */
	private RowMapper<Gyro> getRowMapper() {
		return (rs, num) -> {
			Gyro gyro = new Gyro();
			gyro.setId(rs.getString("ID"));
			gyro.setName(rs.getString("NAME"));
			gyro.setCjms(rs.getString("CJMS"));
			gyro.setCjpl(rs.getString("CJPL"));
			gyro.setOdr(rs.getString("ODR"));
			gyro.setLastFlushTime(rs.getString("LASTFLUSHTIME"));
			return gyro;
		};
	}
}